<template>
  <div>
    <div class="top">
      <div style="margin-top: 20px">
        <!-- 品牌管理 -->
        <template>
          <div class="block">
            <span class="demonstration">日期</span>
            <el-date-picker
              class="rqk"
              v-model="value1"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
        </template>
      </div>

       <div style="margin-top: 20px">
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="搜索" style="margin-left: 50px">
            <el-input
              v-model="params.name"
              placeholder="按品牌查找"
            ></el-input>
          </el-form-item>

          <el-button
            type="primary"
            icon="el-icon-search"
            style="margin-left: 10px"
            @click="getList(1)"
            >查询</el-button
          >

          <el-button
            type="danger"
            icon="el-icon-plus"
            style="margin-left: 10px"
            @click="add"
            >增加</el-button
          >

          <el-button
            type="warning"
            icon="el-icon-delete"
            style="margin-left: 10px"
            @click="removeMore"
            >批量删除</el-button
          >
        </el-form>
      </div>
    </div>

    <div class="bg">
      <el-table
        :data="rows"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
      <!-- 全选 -->
        <el-table-column type="selection" width="55"> </el-table-column>

        <el-table-column label="图片" prop="img">
          <template slot-scope="scope">
          <img style="width:40px;height:40px"  v-if="scope.row.img" :src="scope.row.img" />
          <span v-else>+</span>
          <input ref="file" style="display:none;" type="file" multiple accept="image/*" @change="changeFile">
          </template>
        </el-table-column>

        <el-table-column label="品牌" prop="name"> </el-table-column>


        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit-outline"
              @click="Edit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除此数据吗？"
              @confirm="remove(scope.row)"
            >
              <el-button
                style="margin-left: 5px"
                slot="reference"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="button">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="getList"
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
        <el-dialog :title="form._id ? '修改' : '新增'" :visible.sync="dialogFormVisible" width="400px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <!-- 图片 -->
        <el-form-item label="图片" prop="img">
          <div @click="openFile" class="jh">
          <img style="max-width:100%;max-height:100%" v-if="form.img" :src="form.img" />
          <span v-else>+</span>
        </div>
        <!-- 获取图片地址 -->
          <el-input type="text" v-model="form.img"></el-input>
        </el-form-item>
        <!-- 品牌 -->
        <el-form-item label="品牌" prop="name">
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>

        <!-- 按钮 -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import api from '@/api'
export default {
  name: "pinpai",
  components: {},
  data() {
    return {
        params: {
        name: "",//搜索字段
        pageNum: 1,
        pageSize: 5,
      },
      form: {
        _id:0,
        img: "",
        
        name: "",
      },
      rules: {
        img: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        name: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
      
      },
      currentPage: 1,
      rows: [],
      value1: "",
      value2: "",
      dialogFormVisible: false,
      total: 0,
      selecteds:[]
    };
  },
  methods: {
        //打开选择上传文件
    openFile(){
      // let fileElement = document.getElementById('file')//id="file"
      let fileElement = this.$refs.file//ref="file"
      fileElement.click()
    },
    //选择上传文件
    changeFile(e){
      let files = e.target.files
      let formData = new FormData()
      formData.append('file',files[0])

      this.$http({
        url:'/upload',
        method:'POST',
        data:formData
        
      }).then(res => {
        if(res.path) this.form.img = api.baseURL + '/' + res.path.slice(0,7) + '/' + res.path.slice(8)
      })
      
    },
       //编辑
    Edit(row) {
      this.form = row
      this.dialogFormVisible = true;
    },
 
    add() {
      //初始化
       this.form= {
        //  type: "news",
        _id:0,
        img: '',
        url: '',
        name: '',
      }
      this.dialogFormVisible = true;
    },
    //新增提交
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.indexId = this.form._id
          this.$http({
            url: "/admin/shangpin/pinpai",
            method: this.form.indexId ? 'PUT' : 'POST',//根据indexId判断是新增还是修改
            data: this.form,
          }).then((res) => {
            if (!res.errorMsg) {
              this.dialogFormVisible = false;
              this.getList(this.form.indexId ? undefined : 1);
            }
          });
        }
      });
    },
    getList(pageNum) {
      if (pageNum) this.params.pageNum = pageNum;
      this.$http({
        url: '/admin/shangpin/pinpai',
        params: this.params,
      }).then((res) => {
        this.total = res.total;
        this.rows = res.rows;
      });
    },


    handleSelectionChange(rows){
      //存储选中数据
      this.selecteds = rows
    },
    //删除
    remove(row) {
      console.log(row)
            this.$http({
            url: "/admin/shangpin/pinpai",
            method: "DELETE",
            params:{indexId:row._id}
          }).then((res) => {
            if (!res.errorMsg) {
              this.getList(1);
            }
          });
    },
    //批量删除
    removeMore(){
      //获取选中的数据
      let checkedRowsPrmose = []
      let success = [],fail = []
      for(let i = 0;i<this.selecteds.length;i++){
        checkedRowsPrmose.push(
          new Promise(resovle => {
            let row = this.selecteds[i]
            this.$http({
            url: "/admin/shangpin/pinpai",
            method: "DELETE",
            params:{indexId:row._id}
          }).then((res) => {
            if (!res.errorMsg) {
              success.push(row._id)
            }else{
              fail.push(row._id)
            }
            resovle()
          });
          })
        )
      }
      this.$confirm('是否删除数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
              Promise.all(checkedRowsPrmose).then(() => {
        this.$message({
          message:`批量删除完成，成功删除${success.length}条数据`,
          duration:3000
        });
        this.getList(1)
      })
        })
      //删除
 
    },
    //修改pagesize
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getList(1);
    },

  },
  created() {
    this.getList();
  },
  mounted() {},
};
</script>

<style>
.top {
  display: flex;
  width: 90%;
  margin-left: 50px;
  margin-top: 20px;
  background: #fff;
  /* background: red; */
}
.rqk {
  margin-left: 20px;
}

.bg {
  width: 90%;
  margin-top: 10px;
  margin-left: 50px;
}
.jh{
  overflow: hidden;
  width:100px;
  height:100px;
  font-size:32px;
  border:1px dashed #ccc;
  line-height:100px;
  text-align: center;
}
.button {
  width: 90%;
  margin-top: 20px;
  margin-left: 50px;
}
</style>
